/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Database;

import Entity.Post;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sony
 */
public class PostData {

    public static int insertPost(Post post) throws ClassNotFoundException, SQLException {
        Connection cn = DataAcess.ConnectionDatabase();
        cn.setAutoCommit(false);
        try {

            String sql = "insert into Post(users_id, content, timepost) values (?,?,?)";
            PreparedStatement ps = cn.prepareStatement(sql);
            ps.setInt(1, post.getUsers_id());
            ps.setString(2, post.getContent());
            ps.setDate(3, post.getTimepost());
            ps.executeUpdate();

            String selectSql = "select Top 1 id  from Post Order By id DESC";
            PreparedStatement selectPs = cn.prepareStatement(selectSql);
            ResultSet rsSelect = selectPs.executeQuery();
            int rsCount = 0;
            if (rsSelect.next()) {
                rsCount = rsSelect.getInt("id");
            }
            cn.commit();
            return rsCount;
        } catch (SQLException ex) {
            Logger.getLogger(PostData.class.getName()).log(Level.SEVERE, null, ex);
            cn.rollback();
            return 0;
        } finally {
            cn.close();
        }
    }

    public static ArrayList<Post> getAllPost(int id) throws ClassNotFoundException, SQLException {
        ArrayList<Post> listPost = new ArrayList<Post>();
        Connection cn = DataAcess.ConnectionDatabase();
        try {
            String sql = "select * from Post Order By id DESC";
            PreparedStatement ps = cn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Post post = new Post();
                post.setId(rs.getInt("id"));
                post.setUsers_id(rs.getInt("users_id"));
                post.setContent(rs.getString("content"));
                post.setTimepost(rs.getDate("timepost"));
                post.setComment_id(rs.getString("comment_id"));
                listPost.add(post);
            }
            return listPost;
        } catch (SQLException ex) {
            Logger.getLogger(PostData.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } finally {
            cn.close();
        }
    }
}
